package com.wanmait.spacesys.controller;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.wanmait.spacesys.dao.MyCollectionDAO;
import com.wanmait.spacesys.dao.UpdateUserinfoCenterDAO;
import com.wanmait.spacesys.vo.Userinfo;

/**
 * 控制层:个人信息修改密码
 */
@WebServlet("/UpdatePasswordController")
public class UpdatePasswordController extends BaseController {
	
	
	
	    
		protected void changeuserpass(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
			UpdateUserinfoCenterDAO.getUpdateUserinfoCenterDAO().userinfoFindById(userinfo.getId());
			int count=MyCollectionDAO.getMyCollectionDAO().getCount(userinfo.getId());
	        request.getSession().setAttribute("count", count);
            this.redirect("/web/user/changeuserpass.jsp", request, response);
			
		}
	
	
	    //修改用户密码
		protected void updateUserinfoPassword(HttpServletRequest request, HttpServletResponse response)
					throws ServletException, IOException {
			    //获得前端的新密码
				String password=request.getParameter("password");
				//获得前端原密码
				String primaryPassword=request.getParameter("primaryPassword");
				Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
				if(userinfo!=null) {
					System.out.println(primaryPassword);
					System.out.println(userinfo.getPassword());
					if(!userinfo.getPassword().equals(primaryPassword)) {
						//原密码错误
				/* request.getSession().setAttribute("errMsg", 1); */
						this.redirect("/web/user/changeuserpass.jsp", request, response);
					}else {
					userinfo.setPassword(password);
					UpdateUserinfoCenterDAO.getUpdateUserinfoCenterDAO().updatePassword(userinfo);
					this.redirect("/web/userLogin.jsp", request, response);
					}
				}
		}
		
		//判断原密码
		protected void passwordAjax(HttpServletRequest request, HttpServletResponse response)
				throws ServletException, IOException {
			//获得前端原密码
			String primaryPassword=request.getParameter("pass");
			Userinfo userinfo = (Userinfo) request.getSession().getAttribute("userinfo");
			if(userinfo!=null) {
			 PrintWriter out = response.getWriter();
			 if(userinfo.getPassword().equals(primaryPassword)) {
				 out.print("ok");
			 }else {
				 out.print("no");
			 }
			 
			}
			
		}

	@Override
	protected void doDefault(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.updateUserinfoPassword(request, response);
		
	}

}
